﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using  System.Data.SqlClient;
using Dapper;
using UnityCommon;

namespace Dal
{
    public class DBBase<T>
    {
        public List<T> GetAll()
        {
            string tableName = typeof (T).Name;

            string cols = string.Empty;

            for (int i = 0; i < typeof(T).GetProperties().Length; i++)
            {
                string col = typeof (T).GetProperties()[i].Name;

                cols += col + ",";
            }
            if (cols.EndsWith(","))
            {
               cols = cols.Substring(0, cols.Length - 1);
            }
            string sql = string.Format("SELECT {0} FROM {1}",cols,tableName);

            List<T> list = new List<T>();

            using (var conn  = new SqlConnection(Common.GetConstr("Sqlcon")))
            {
                if (conn.Query(sql).Any())
                {
                    list = conn.Query<T>(sql).ToList();
                }
            }
            return list;
        }

        //public List<T> GetByWhere()
        //{
            
        //}

        public int InsertSingle(T t)
        {
            string sql = "INSERT INTO {0}({1}) VALUES({2})";

            Type s = typeof (T);

            string tablename = s.Name;

            string insertPara = string.Empty;

            string valuePara = string.Empty;

            for (int i= 0; i < s.GetProperties().Length; i++)
            {
                insertPara += s.GetProperties()[i].Name+",";

                valuePara += "@"+s.GetProperties()[i].Name+",";
            }
            insertPara = insertPara.EndsWith(",") ? insertPara.Substring(0, insertPara.Length - 1) : insertPara;
            valuePara = valuePara.EndsWith(",") ? valuePara.Substring(0, valuePara.Length - 1) : valuePara;

            sql = string.Format(sql, tablename, insertPara, valuePara);

            var result = 0;

            using (var conn = new SqlConnection(Common.GetConstr("Sqlcon")))
            {
                conn.Open();

                result = conn.Execute(sql, t);
            }
            return result;
        }
    }
}
